<template>
  <article class="page page-txt-split">
    <h4 class="text-center">文本分割器</h4>
    <form class="form">
      <div class="form-group">
        <fieldset>
          <legend>分割设置</legend>
          <div class="row-flex" align="center">
            <div class="row-flex-prefix">分割文件</div>
            <div class="row-flex-main"><input class="form-control" type="text" v-model="fromPath" /></div>
            <div class="row-flex-suffix"><x-button @click="setFromPath">选择...</x-button></div>
          </div>
          <div class="row-flex" align="center">
            <div class="row-flex-prefix">保存位置</div>
            <div class="row-flex-main"><input class="form-control" type="text" v-model="toPath" /></div>
            <div class="row-flex-suffix"><x-button @click="setToPath">选择...</x-button></div>
          </div>
        </fieldset>
      </div>
      <div class="form-group row">
        <div class="col-6">
          <fieldset>
            <legend>分割方式</legend>
            <div class="row-flex" align="center">
              <label class="row-flex-prefix"><input class="form-check-input" type="radio" value="size" v-model="splitMode">每份大小为</label>
              <div class="row-flex-main"><input class="form-control" type="text" v-model="splitModeSize" /></div>
              <div class="row-flex-suffix">KB</div>
            </div>
            <div class="row-flex" align="center">
              <label class="row-flex-prefix"><input class="form-check-input" type="radio" value="count" v-model="splitMode">平均分配为</label>
              <div class="row-flex-main"><input class="form-control" type="text" v-model="splitModeCount" /></div>
              <div class="row-flex-suffix">份</div>
            </div>
            <div class="row-flex" align="center">
              <label class="row-flex-prefix"><input class="form-check-input" type="radio" value="rows" v-model="splitMode">每份行数为</label>
              <div class="row-flex-main"><input class="form-control" type="text" v-model="splitModeRows" /></div>
              <div class="row-flex-suffix">行</div>
            </div>
          </fieldset>
        </div>
        <div class="col-6">
          <fieldset>
            <legend>设置名称</legend>
            <div class="row-flex" align="center">
              <div class="row-flex-prefix"><input class="form-check-input" type="radio" value="0" v-model="customName">自定义名称</div>
              <div class="row-flex-main"><input class="form-control" type="text" v-model.trim="fileName" /></div>
              <div class="row-flex-suffix">+ _序号</div>
            </div>
            <div class="row-flex" align="center">
              <input class="form-check-input" type="radio" value="1" v-model="customName">自动以数字符号命名（例：1.txt,2.txt...）
            </div>
          </fieldset>
        </div>
      </div>
      <div class="form-group">
        <fieldset>
          <legend>信息概览</legend>
          <div class="row-flex" align="center">
            <div class="row-flex-prefix">分割文件：</div>
            <div class="row-flex-main text-grey text-left">
              <span>大小（{{splitBeforeInfo.size || '--'}}）</span>，
              <span>行数（{{splitBeforeInfo.rows || '--'}}）</span>
            </div>
          </div>
          <div class="row-flex" align="center">
            <div class="row-flex-prefix">分割结果：</div>
            <div class="row-flex-main text-grey text-left">
              <span>文件个数（{{splitAfterInfo.count || '--'}}）</span>，
              <span>单个文件大小（{{splitAfterInfo.size || '--'}}）</span>
            </div>
          </div>
        </fieldset>
      </div>
      <div class="form-group text-center">
        <x-button type="primary" @click="getSplitAfterInfo">结果预览</x-button>
        <x-button type="primary" @click="splitTxt">开始分割</x-button>
      </div>
    </form>
  </article>
</template>

<script>
const fs = global.require('fs')
const path = global.require('path')
const {remote} = global.require('electron')
const {dialog} = remote
const selfWindow= remote.getCurrentWindow()

export default {
  name: 'txt-split',
  data () {
    return {
      fromPath: '',
      toPath: '',
      splitMode: 'size',
      splitModeSize: '',
      splitModeCount: '',
      splitModeRows: '',
      fileName: '',
      customName: '0',
      fileData: '',
      fileSize: 0,
      splitBeforeInfo: {size: '', rows: ''},
      splitAfterInfo: {size: '', rows: '', count: ''},
      splitingCount: 0
    }
  },
  methods: {
    resetData () {
      this.fileData = ''
      this.fileSize = 0
      this.splitBeforeInfo = {size: '', rows: ''}
      this.splitAfterInfo = {size: '', rows: '', count: ''}
      this.splitingCount = 0
    },
    // 设置分割文件位置
    setFromPath () {
      let filePaths = dialog.showOpenDialogSync(selfWindow, {
        title: '选择文件',
        buttonLabel:'确定',
        defaultPath: this.$sharedObject('desktopPath'),
        properties: ['openFile']
      })
      if (filePaths instanceof Array && filePaths.length > 0) {
        this.fromPath = filePaths[0]
        this.resetData()
        this.getSplitBeforeInfo()
      }
    },
    // 设置保存位置
    setToPath () {
      let filePaths = dialog.showOpenDialogSync(selfWindow, {
        title: '选择目录',
        buttonLabel:'确定',
        defaultPath: this.$sharedObject('desktopPath'),
        properties: ['openDirectory']
      })
      console.log(filePaths)
      if (filePaths instanceof Array && filePaths.length > 0) {
        this.toPath = filePaths[0]
      }
    },
    // 获取分割前的文件信息
    getSplitBeforeInfo () {
      this.splitBeforeInfo = {size: '', rows: ''}
      if (!fs.existsSync(this.fromPath)) {
        this.$toast('待分割文件不存在')
        return
      }
      fs.stat(this.fromPath, (err, data) => {
        console.log(err, data)
        if (err) {
          this.$toast(err)
          return
        }
        if (!data.isFile()) {
          this.$toast('待分割文件不存在')
          return
        }
        this.fileSize = data.size || 0
        this.$set(this.splitBeforeInfo, 'size', this.$jstools.formatFileSize(data.size))
      })
    },
    // 计算分割后的文件信息
    getSplitAfterInfo (callback) {
      this.splitAfterInfo = {size: '', rows: '', count: ''}
      if (this.splitingCount > 0) {
        this.$toast('正在处理，请稍后...')
        return
      }
      if (!this.fromPath) {
        this.$toast('请选择待分割文件')
        return
      }
      if (!this.toPath) {
        this.$toast('请设置分割后文件的保存位置')
        return
      }
      let splitMode = this.splitMode.substring(0, 1).toUpperCase() + this.splitMode.substring(1)
      if ((this[`splitMode${splitMode}`] || 0) <= 0) {
        this.$toast('分割方式数据错误')
        return
      }
      fs.readFile(this.fromPath, (err, data) => {
        console.log(err, data)
        if (err) {
          this.$toast(err)
          return
        }
        this.fileData = data.toString()
        let rowsCount = this.fileData.split('\n').length
        this.$set(this.splitBeforeInfo, 'rows', rowsCount)
        if (this.splitMode === 'size') {
          this.$set(this.splitAfterInfo, 'size', `${this.splitModeSize}KB`)
          this.$set(this.splitAfterInfo, 'count', Math.ceil(this.fileSize / (this.splitModeSize * 1024)))
        } else if (this.splitMode === 'count') {
          this.$set(this.splitAfterInfo, 'count', this.splitModeCount)
          this.$set(this.splitAfterInfo, 'size', this.$jstools.formatFileSize(Math.ceil(this.fileSize / this.splitModeCount)))
        } else if (this.splitMode === 'rows') {
          this.$set(this.splitAfterInfo, 'count', Math.ceil(rowsCount / this.splitModeRows))
          this.$set(this.splitAfterInfo, 'size', '--')
        }
        callback && callback()
      })
    },
    // 分割文件
    splitTxt () {
      this.getSplitAfterInfo(() => {
        this.splitTxtStep2(this.splitTxtStep1())
      })
    },
    // 分割文件STEP1·整理分割后各个文件的数据
    splitTxtStep1 () {
      let result = []
      let fileDataLength = this.fileData.length
      if (this.splitMode === 'size') {
        let len = Math.floor((this.splitModeSize * 1024 / this.fileSize) * fileDataLength)
        let start = 0
        while (start < fileDataLength) {
          result.push(this.fileData.substr(start, len))
          start += len
        }
      } else if (this.splitMode === 'count') {
        let len = Math.ceil(fileDataLength / this.splitAfterInfo.count)
        let start = 0
        while (start < fileDataLength) {
          result.push(this.fileData.substr(start, len))
          start += len
        }
      } else if (this.splitMode === 'rows') {
        let rowsArr = this.fileData.split('\n')
        rowsArr.forEach((v, i) => {
          let index = Math.floor(i / this.splitModeRows)
          result[index] = (result[index] || '') + '\n' + v
        })
      }
      return result
    },
    // 分割文件STEP2·输出文件
    splitTxtStep2 (fileDataArr) {
      if ((fileDataArr || []).length === 0) return
      let tasklist = []
      fileDataArr.forEach((v, i) => {
        let fn = (this.customName === '0' ? `${this.fileName}_${i + 1}` : (i + 1)) + '.txt'
        let fp = path.join(this.$sharedObject('desktopPath'), fn)
        tasklist.push(this.$sharedObject('jstoolsNode').writeFile(fp, Buffer.from(v)))
      })
      this.splitingCount++
      Promise.all(tasklist).finally(() => {
        this.splitingCount--
        this.$toast('处理完毕')
      })
    },
  }
}
</script>

<style scoped lang="less">
@import "~@/assets/css/_mixins.less";
@import "~@/assets/css/_color.less";
.row-flex {
  & + .row-flex {
    margin-top: 1em;
  }
  .row-flex-suffix {
    min-width: 2em;
  }
}
.form-group {
  fieldset {
    height: 100%;
  }
}
</style>
